package cn.sunxiansheng.log4j2.listener;

import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.logging.LoggingApplicationListener;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 * Description: 配置文件已加载，Environment 对象已初始化
 * 使用 ApplicationEnvironmentPreparedEvent 读取 application.yml 文件中的 sun-rays-log4j2.home 和 sun-rays-log4j2.module 配置
 *
 * @Author sun
 * @Create 2024/12/13 23:53
 * @Version 1.0
 */
public class ApplicationEnvironmentPreparedListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered {

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment environment = event.getEnvironment();

        // 获取 log.home 属性并提供默认值
        String logHome = environment.getProperty("sun-rays.log4j2.home", "./logs");
        if ("./logs".equals(logHome)) {
            System.err.println("WARNING: sun-rays.log4j2.home 属性未设置，使用默认值: " + logHome);
        }

        // 将属性设置为系统属性
        System.setProperty("log.home", logHome);
    }

    /**
     * 当前监听器的启动顺序需要在日志配置监听器的前面，保证在日志文件初始化之前读取 application.yml 的配置。
     *
     * @return
     */
    @Override
    public int getOrder() {
        return LoggingApplicationListener.DEFAULT_ORDER - 1;
    }
}
